//axios 拦截器 配置

import axios from 'axios'
import config from '@/utils/config'
import {Message} from 'element-ui'
import router from '@/router'

const service = axios.create({
    baseURL: config.baseURL,
    timeout: 0
})

service.interceptors.request.use(
    conf => {
        localStorage.token && (conf.headers.__token = localStorage.token)
        return conf
    }
)

service.interceptors.response.use(
    res => {
        if (res.data.code === 700) {
            Message({
                message: '登录已过期,请重新登录!',
                type: 'error',
                duration: 5000
            })
            localStorage.clear()
            router.push('/')
        } else if (res.data.code === 200) {
            return res.data
        } else {
            Message({
                message: res.data.msg,
                type: 'warning',
                duration: 2000
            })
            return Promise.reject(res.data.msg)
        }
    },

    err => {
        err.message = '网络连接失败，请和运营商联系'
        if (err.response) {
            err.status = err.response.status
            switch (err.response.status) {
                case 400:
                    err.message = '请求错误'
                    break
                case 401:
                    err.message = '未授权，请登录'
                    break
                case 403:
                    err.message = '拒绝访问'
                    break
                case 404:
                    err.message = `请求地址出错 ${err.response.config.url}`
                    break
                case 408:
                    err.message = '请求超时'
                    break
                case 500:
                    err.message = '服务器内部错误'
                    break
                case 501:
                    err.message = '服务未实现'
                    break
                case 502:
                    err.message = '网关错误'
                    break
                case 503:
                    err.message = '服务不可用'
                    break
                case 504:
                    err.message = '网关超时'
                    break
                case 505:
                    err.message = 'HTTP版本不受支持'
                    break
                default:
                    err.message = '未知错误'
                    break
            }
        }
        Message({
            message: err.message,
            type: 'error',
            duration: 5000
        })
        return Promise.reject(err)
    }
)

export default service
